/**
 * Created by pankajmishra on 06/12/14.
 */
define(['jquery','module/template/homeTemplate', 'mustache',
    'module/common/utils',
    'module/common/form',
    'module/people/render'
], function($, template, mustache, utils, form, render){



    var SearchPeople = function (updateDom, searchDom){

        var thisVar = this, advSearch = null, processUser = render.processUserResult;


        this.getAdvanceSearchParam = function(advSearch){
            var formUtil = new form(advSearch);
            return formUtil.getFormParam();
        };

        this.buildAdvanceSearch = function(){
            advSearch = $( template['people-search-form']);
            advSearch.find('.js_adv_srch').click(function(e){
                advSearch.find('.js_adv_body').slideToggle();
            });
            advSearch.find('.js_search_btn').click(function(e){
                e.preventDefault();

                var adv = thisVar.getAdvanceSearchParam(advSearch);
                var keys = Object.keys(adv);
                if(keys.length > 0){
                    $.getJSON('/people/advSearch',adv , 'json').done(function(response){
                        thisVar.showSearchResult(processUser(response));
                    }).fail(function(failRes){

                    });
                    advSearch.find('.js_adv_body').slideToggle();
                } else {

                    alert('Please specify at least one field');
                }
            });
            return advSearch;
        };

        this.removeSearchResults = function(){
            updateDom.children().each(function(){
                if(this !== advSearch[0] ){
                    $(this).remove();
                }
            });
        };

        this.showSearchResult = function (response){
            thisVar.removeSearchResults();
            if(response.length == 0){
                updateDom.append($( template['people-search-error']));
                return;
            }
            $.each(response, function(index, user){
                updateDom.append($( mustache.render(template['people-search'], user)));
            });
        }

        this.buildSearchArena = function(response){
            updateDom.empty();
            updateDom.append(thisVar.buildAdvanceSearch());
            thisVar.showSearchResult(response);
        };

        searchDom.on('keydown', function(event){
            // enter
            if(event.keyCode == 13){
                if($(this).val().trim()){
                    $.getJSON('/people/searchPeople', {name : $(this).val() }, 'json').done(function(response){
                        thisVar.buildSearchArena(processUser(response));
                    }).fail(function(failRes){

                    });
                }
            }
        });
    }

    return SearchPeople;
});